package com.smartleanx.module.hrm.util;

import cn.hutool.http.HttpRequest;
import com.smartleanx.framework.common.util.json.JsonUtils;
import com.smartleanx.framework.tenant.core.context.TenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送告警
 *
 * @author tengcj
 * @since 2024/7/25
 */
@Component
@Slf4j
public class WebhookService {

    public static final String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=39cd55bd-7b66-4423-b6f0-f0e8aba01531";

    @Value("${spring.profiles.active:dev}")
    private String profile;

    @Value("${spring.application.name:HRM}")
    private String serviceName;

    public void sendMessage(String message) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("msgtype", "markdown");

            Map<String, String> messageMap = new HashMap<>();
            paramMap.put("markdown", messageMap);

            String content = "服务发生异常，请相关同学注意。\n" +
                    "         >环境:<font color=\"info\">%s</font>\n" +
                    "         >服务名:<font color=\"info\">%s</font>\n" +
                    "         >租户id:<font color=\"info\">%s</font>\n" +
                    "         >异常信息:<font color=\"warning\">%s</font>";

            messageMap.put("content", String.format(content, profile, serviceName, TenantContextHolder.getTenantId(), message));

            String body = HttpRequest.post(url)
                    .header("Content-Type", "application/json")
                    .body(JsonUtils.toJsonString(paramMap))
                    .execute().body();
        } catch (Exception e) {
            log.error("发送告警失败, 原告警信息{}", message);
            log.error("发送告警失败", e);
        }
    }

}
